<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends CI_Controller {
	public function index(){
		if($this->session->userdata('user_id') == '' || $this->session->userdata('user_name') == ''){
			$this->load->helper(array('url'));
			redirect('/user/login', 'location', 301);
		}
		else{
			#$this->session->userdata('user_id').'|'.$this->session->userdata('user_name');
			$this->layout->setLayout('default');
			$this->layout->setTitle('Administrator | Home');
			$month = isset($_GET['month']) ? quotes_to_entities($_GET['month']) : date('Y-m');
			$filter = " AND receive_date BETWEEN '" . $month."-01 00:00:00" . "' AND '" . $month."-31 23:59:59" . "'";
		
			// get earning data
			$sqlThisMonthEarning = "SELECT sms_cost AS subtotal, 
									   DATE_FORMAT(receive_date, '%d-%m-%Y') AS earn_date
									FROM tdx_sms_stat WHERE 1=1 $filter";
			$monthQuery = $this->db->query($sqlThisMonthEarning);
			if ($monthQuery->num_rows() > 0){
				$arrData = array();
				$total = 0;
				foreach ($monthQuery->result_array() as $row){
					$arrData[$row['earn_date']] += intval($row['subtotal']);
					$total += intval($row['subtotal']);
				}
			}
			if(isset($_GET['date'])){
				$today = $_GET['date'];
				$sqlToday = "SELECT SUM(sms_cost) AS subtotal
									FROM tdx_sms_stat WHERE receive_date BETWEEN '" . $today." 00:00:00" . "' AND '" . $today." 23:59:59" . "'";
				$todayQuery = $this->db->query($sqlToday);
				$todayData = $todayQuery->row();
				$strDate = 'Ngày '.$_GET['date'];
				$data['earn_today'] = intval($todayData->subtotal);
			}
			else{
				$strDate = 'Hôm nay';
				$data['earn_today'] = intval($arrData[date('d-m-Y')]);
			}
			$data['earn_yesterday'] = intval($arrData[date('d-m-Y', strtotime('-1 day'))]);
			$data['earn_this_month'] = $total;
			$data['str_date'] = $strDate;
			$data['month_data'] = $arrData;
			
			$this->layout->view(THEME_DIR.'/home_index', $data);
		}
	}
}